package com.weike.yuanding.controller;

import cn.hutool.core.date.DateUtil;
import com.weike.yuanding.core.domain.R;
import com.weike.yuanding.utils.AliOssUtil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.*;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.encode.VideoAttributes;
import ws.schild.jave.process.ProcessLocator;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;

@RestController
@RequestMapping("/common")
public class UploadController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public R uploadFile(@RequestParam("file") MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String fileFormat = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + fileFormat;

        String videoOssPath = null;
        try {
            videoOssPath = aliOssUtil.upload(file.getBytes(), fileName);
        } catch (IOException e) {
            throw new RuntimeException("视频上传失败", e);
        }

        // 保存临时视频文件到本地，用于抽帧
        File tempVideoFile = null;
        File tempImageFile = null;
        String coverOssPath = null;
        try {
            tempVideoFile = File.createTempFile("upload_", fileFormat);
            file.transferTo(tempVideoFile);

            // 抽取第一帧并保存为临时图片
            tempImageFile = File.createTempFile("cover_", ".jpg");
            extractFirstFrame(tempVideoFile.getAbsolutePath(), tempImageFile.getAbsolutePath());

            // 上传封面图到 OSS
            byte[] coverBytes = Files.readAllBytes(tempImageFile.toPath());
            String coverFileName = UUID.randomUUID().toString() + ".jpg";
            coverOssPath = aliOssUtil.upload(coverBytes, coverFileName);

        } catch (Exception e) {
            throw new RuntimeException("视频封面处理失败", e);
        } finally {
            // 删除临时文件
            if (tempVideoFile != null) tempVideoFile.delete();
            if (tempImageFile != null) tempImageFile.delete();
        }

        // 构建返回
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("status", "success");
        resultMap.put("url", videoOssPath);
        resultMap.put("cover", coverOssPath);
        resultMap.put("uploadTime", DateUtil.format(new Date(), "YYYY-MM-dd HH:mm:ss"));
        resultMap.put("size", file.getSize());

        return R.ok(resultMap);
    }



    public void extractFirstFrame(String videoPath, String outputPath) {
        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoPath)) {
            grabber.start();

            Java2DFrameConverter converter = new Java2DFrameConverter();
            Frame frame;
            // 避免首帧可能为空，尝试多取几帧
            for (int i = 0; i < 5; i++) {
                frame = grabber.grabImage();
                if (frame != null) {
                    BufferedImage image = converter.convert(frame);
                    ImageIO.write(image, "jpg", new File(outputPath));
                    break;
                }
            }

            grabber.stop();
        } catch (IOException e) {
            throw new RuntimeException("抽取视频第一帧失败", e);
        }
    }

}
